package com.hrt.common.web;

import com.btcode.common.AbstractSingleton;
import com.btcode.db.sqlparameter.PageInfo;
import com.btcode.orm.filter.IFilter;
import com.btcode.orm.model.IModel;
import com.btcode.orm.model.ModelPageResult;
import com.btcode.web.core.unit.WebContext;
import com.hrt.common.db.CommonDBManager;
import java.util.List;

/**
 * 通用的server逻辑
 *
 * @author gislin
 */
public class BaseService extends AbstractSingleton implements IService {

    @Override
    public void create(IModel model) {
        CommonDBManager.getORMExecuter().create(model);
    }

    @Override
    public void creates(List<? extends IModel> models) {
        CommonDBManager.getORMExecuter().creates(models);
    }

    @Override
    public void update(IModel model) {
        CommonDBManager.getORMExecuter().update(model);
    }

    @Override
    public void delete(IModel model) {
        CommonDBManager.getORMExecuter().delete(model);
    }

    @Override
    public IModel getModel(IModel model) {
        return CommonDBManager.getORMExecuter().getModel(model);
    }

    @Override
    public IModel getModelRequest(Class<? extends IModel> modelClass) {
        String parameterType = WebContext.getRequest().getHeader("Parameter-Type");
        IModel requestModel;
        if (parameterType != null && parameterType.contains("un-flatten")) {//非扁平化
            requestModel = JsonRequestUnit.getModel(modelClass,
                                            JsonRequestUnit.getString("data"));
        }
        else {
            requestModel = RequestUnit.getModel(modelClass);
        }
        return CommonDBManager.getORMExecuter().getModel(requestModel);
    }

    @Override
    public ModelPageResult listModel(Class<? extends IModel> modelClass,
        List<IFilter> whereFilters,String orderString, PageInfo pageInfo) {
        return CommonDBManager.getORMExecuter().getModelList(modelClass, whereFilters,orderString,pageInfo);
    }

    @Override
    public ModelPageResult listModelRequest(Class<? extends IModel> modelClass) {

        List<IFilter> filters = RequestUnit.getModelFilter(modelClass);
        String orderString = RequestUnit.getString("orderString");
        PageInfo pageInfo = RequestUnit.getPageInfo();
        return CommonDBManager.getORMExecuter().getModelList(modelClass, filters,orderString,pageInfo);
    }

}
